package com.example.demo.interceptor;

import com.example.demo.service.BookService;
import com.example.demo.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;

@Component
public class AddUserInterceptor implements HandlerInterceptor {
    private BookService bookService;
    private UserService userService;
    @Autowired
    public AddUserInterceptor(BookService bookService, UserService userService) {
        this.bookService = bookService;
        this.userService = userService;
    }
    // 在控制器之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("borrow_list", bookService.getBorrowList());
        request.setAttribute("book_count", bookService.getBookList().size());
        request.setAttribute("book_list", bookService.getBookList().keySet());
        request.setAttribute("student_count", userService.getStudentList().size());
        request.setAttribute("student_list", userService.getStudentList());
        request.setAttribute("book_list_status", new ArrayList<>(bookService.getBookList().values()));
        return true;
    }

    // 在控制器之后、视图渲染之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(modelAndView != null) {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            modelAndView.addObject("nickname", user.getUsername());
            modelAndView.addObject("borrow_list", request.getAttribute("borrow_list"));
            modelAndView.addObject("book_count", request.getAttribute("book_count"));
            modelAndView.addObject("book_list", request.getAttribute("book_list"));
            modelAndView.addObject("student_count", request.getAttribute("student_count"));
            modelAndView.addObject("student_list", request.getAttribute("student_list"));
            modelAndView.addObject("book_list_status", request.getAttribute("book_list_status"));
        }
    }
}
